import * as vscode from 'vscode';
import { TaskInfo, Configuration } from '../proto-gen';

import { ProjectTaskApi } from '../proto-gen/api';
import { getProjectToken } from '../utils/tokenUtils';
import { unix } from 'moment';
import { getBasePath } from '../utils/basePathUtils';

export class MyTaskProvider implements vscode.TreeDataProvider<TaskItem> {
    private _onDidChangeTreeData: vscode.EventEmitter<TaskItem | undefined | void> = new vscode.EventEmitter<TaskItem | undefined | void>();
    readonly onDidChangeTreeData: vscode.Event<TaskItem | undefined | void> = this._onDidChangeTreeData.event;


    getTreeItem(element: TaskItem): vscode.TreeItem | Thenable<vscode.TreeItem> {
        return element;
    }
    getChildren(element?: TaskItem | undefined): vscode.ProviderResult<TaskItem[]> {
        if (element) {
            return [];
        } else {
            const basePath = getBasePath();
            if (basePath == null) {
                return [];
            }
            const api = new ProjectTaskApi(new Configuration({
                basePath: basePath.basePath,
            }));
            const tokenInfo = getProjectToken();
            if (tokenInfo == null) {
                return [];
            }
            return new Promise<TaskItem[]>((resolve, _) => {
                api.projectProjectIdTaskMyGet(tokenInfo.projectId, "unclose", basePath.token).then(res => {
                    const result = res.data.map(item => new TaskItem(item));
                    resolve(result);
                }).catch(e => {
                    console.log(e);
                    vscode.window.showErrorMessage(`${e}`);
                    resolve([]);
                });
            });
        }
    }
    sync() {
        this._onDidChangeTreeData.fire();
    }
}


export class TaskItem extends vscode.TreeItem {
    constructor(taskInfo: TaskInfo) {
        super(taskInfo.title ?? "");
        this.contextValue = 'task';
        this.id = taskInfo.taskId;
        this.collapsibleState = vscode.TreeItemCollapsibleState.None;
        this.iconPath = new vscode.ThemeIcon("tasklist");
        const tooltip = `
- 状态: ${this.stateStr(taskInfo)}
- 创建者: ${taskInfo.createDisplayName ?? ""}
- 执行者: ${taskInfo.execDisplayName ?? ""}
- 检查者: ${taskInfo.checkDisplayName ?? ""}
- 执行贡献: ${taskInfo.execAwardPoint ?? 0}
- 检查贡献: ${taskInfo.checkAwardPoint ?? 0}
- 优先级: ${this.priorityStr(taskInfo)}
- 创建时间: ${taskInfo.createTime == undefined ? "未知" : unix(taskInfo.createTime / 1000).format("YYYY-MM-DD HH:mm:ss")}
- 更新时间: ${taskInfo.updateTime == undefined ? "未知" : unix(taskInfo.updateTime / 1000).format("YYYY-MM-DD HH:mm:ss")}
        `;
        this.tooltip = new vscode.MarkdownString(tooltip);
    }

    private stateStr(taskInfo: TaskInfo): string {
        if (taskInfo.state == undefined) {
            return "";
        }
        if (taskInfo.state == "plan") {
            return "规划中";
        } else if (taskInfo.state == "process") {
            return "处理中";
        } else if (taskInfo.state == "check") {
            return "检查中";
        } else if (taskInfo.state == "close") {
            return "已关闭"
        }
        return "";
    }

    private priorityStr(taskInfo: TaskInfo): string {
        if (taskInfo.priority == undefined) {
            return "";
        }
        if (taskInfo.priority == "low") {
            return "低";
        } else if (taskInfo.priority == "middle") {
            return "中";
        } else if (taskInfo.priority == "high") {
            return "高";
        }
        return "";
    }

    async show(): Promise<void> {
        const basePath = getBasePath();
        if (basePath == null) {
            return;
        }
        const api = new ProjectTaskApi(new Configuration({
            basePath: basePath.basePath,
        }));
        const tokenInfo = getProjectToken();
        if (tokenInfo == null) {
            return;
        }
        await api.projectProjectIdTaskRecordTaskIdShowGet(tokenInfo.projectId, this.id ?? "", basePath.token);
    }

    async shortNote(): Promise<void> {
        const basePath = getBasePath();
        if (basePath == null) {
            return;
        }
        const api = new ProjectTaskApi(new Configuration({
            basePath: basePath.basePath,
        }));
        const tokenInfo = getProjectToken();
        if (tokenInfo == null) {
            return;
        }
        await api.projectProjectIdTaskRecordTaskIdShortNoteGet(tokenInfo.projectId, this.id ?? "", basePath.token);
    }
}